package save_data

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"study5/jysp/model"
	"unicode/utf8"
)

const dirName = "./save_text"

func init(){
	textDirCheck()

}

func textDirCheck(){

	_,err := os.Stat(dirName)

	if os.IsNotExist(err) {
		if err = os.Mkdir(dirName,0777);err != nil{
			panic(err)
		}else{
			fmt.Printf("create dir success :%s\n",dirName)
		}

	}

}

type TextSaver struct {
	CurName string
}

func NewTextSaver(curName string) *TextSaver{
	return &TextSaver{
		CurName:curName,
	}
}

func (s *TextSaver) Save(list []*model.ListUserInfo) (num int,err error){
	file,err := os.Create(dirName+"/"+s.CurName+".txt")
	if err != nil{
		fmt.Printf("create the file err :%s\n",err)
		return
	}
	defer file.Close()

	writer := bufio.NewWriter(file)

	for index,val := range list{
		itemMsg := createMsg(index+1,val)
		_,err = writer.WriteString(itemMsg)
		if err != nil{
			return
		}
		num++

	}
	writer.Flush()

	return
}

func createMsg(index int,info *model.ListUserInfo) string{
	var str string


	str = fmt.Sprintf("%-2d. %s %-5d %s %s %s %s\n",index,formatStr(info.Nickname,20),info.Age,info.Marriage,formatStr(info.Education,10),info.Height,formatStr(info.WorkLocation,6))
	return str
}


func formatStr(str string,needLen int) string{
	spaceCode := 32

	strCount := utf8.RuneCountInString(str)
	need := needLen - strCount
	//strCount := len(str)
	//need := needLen*3 - strCount


	buf := bytes.NewBufferString(str)

	appendSpace := make([]byte,need*2)

	for i := 0; i < len(appendSpace); i++ {
		appendSpace[i] = byte(spaceCode)
	}

	buf.Write(appendSpace)


	return buf.String()
}
